#include "AnimatedSprite.h"

using namespace sf;
using namespace std;

AnimatedSprite::AnimatedSprite(const Image& img, const vector<AnimationDefinition>& defs) : 
Sprite(img), animationTime(0.0f), currentFrame(0), currentAnimation(0)
{
	for (vector<AnimationDefinition>::const_iterator it = defs.begin(); it != defs.end(); ++it) {
		animations[it->name] = *it;
	}
}

void AnimatedSprite::setAnimation(string name)
{
	if (currentAnimation && currentAnimation->name == name) {
		return;
	}
	map<string, AnimationDefinition>::const_iterator it = animations.find(name);
	if (it != animations.end()) {
		currentAnimation = &(it->second);
		animationTime = 0;
		currentFrame = 0;
		SetSubRect(currentAnimation->frames[currentFrame]);
	}
}

void AnimatedSprite::update(float elapsedTime)
{
	if (currentAnimation && currentAnimation->fps > 0) {
		animationTime += elapsedTime;
		if (animationTime >= (1.0f / currentAnimation->fps)) {
			nextFrame();
			animationTime = 0;
		}
		SetSubRect(currentAnimation->frames[currentFrame]);
	}
}

void AnimatedSprite::nextFrame()
{
	currentFrame = 
		(currentFrame >= currentAnimation->frames.size() - 1) ? 0 : currentFrame + 1;
}
